package com.jt9003.controller;

import com.jt9003.pojo.*;
import com.jt9003.service.impl.P_RegistrationServiceimpl;
import com.jt9003.utils.PageUtils;
import com.jt9003.utils.P_NamberUtil;
import com.sun.corba.se.spi.ior.ObjectKey;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

//患者挂号
@RestController
public class P_RegistrationController {

    //获取ServiceImpl对象
    @Autowired
    P_RegistrationServiceimpl pr;

    /**
     * 添加患者信息
     * 每次挂号先判断当前人数是否到达设置的数量，再将当前就诊人数+1
     * 判断身份证号在患者表中是否有存在，如果不存在，则添加患者
     * 如果存在相同患者，则不用在患者表添加数据，添加挂号单信息时，添加该患者id即可
     * 有两个挂号页面，所以添加了sychronized线程锁
     * 同时给患者档案表添加数据
     * @param patient
     * @param register
     * @return
     */
    @RequestMapping("/addpatient")
    @Transactional
    public synchronized  Map addPatient(Patient patient, Register register) {
        Map<String, Object> map = new HashMap<String, Object>();

        //给register的rDate设置当前时间
        register.setrDate(new Date());
        //将拿到的数据封装进map
        Map<String, Object> map1 = new HashMap<String, Object>();

        try {
            //获取当前时间的就诊人数
            Map<String,Object> p_nMap = judgeP_Namber();
            String message = "";
            int pn = 0;
            message = (String)p_nMap.get("message");
            pn = (Integer) p_nMap.get("data")+1;
            if (message!="" && message!=null){
                map.put("patientNamberInfo",message);
                map.put("patientNamber",pn);
                map.put("success", true);
            }else{
                //设置诊号,等于静态变量+1
                register.setrDiagnosisNum((Integer)p_nMap.get("data")+1);

                map1.put("patient", patient);
                map1.put("register", register);
                //调用Service层方法 添加患者信息，底层判断如果是初诊的患者则添加到患者档案
                int count = pr.addpatient(map1);
                if (count > 0) {
                    map.put("message", "添加挂号单成功");
                    map.put("result", count);
                    map.put("success", true);
                } else {
                    map.put("message", "添加挂号单失败");
                    map.put("success", false);
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
            //回滚
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            map.put("message", "程序故障");
            map.put("success", false);
        }
        return map;
    }


    //查询所有未交费挂号单的信息
    @RequestMapping("/selectAllRegister")
    public Map select_Register(@RequestParam(value = "pName2", required = false) String pName2,
                               @RequestParam(value = "time", required = false) String time,
                               @RequestParam(value = "doctorName", required = false) String doctorName,
                               @RequestParam(value = "page", required = false, defaultValue = "1") Integer page,
                               @RequestParam(value = "limit", required = false, defaultValue = "5") Integer limit) {
        Map<String, Object> map = new HashMap<String, Object>();
        Integer index = new Integer(PageUtils.getStart(page, limit));
        List<Register> list = new ArrayList<Register>();
        //获取拿到的时间，拆分开
        String start = "";
        String end = "";
        if (time != null && time != "") {
            String[] strarr = time.split(" - ");    //空格不能去掉，需要按照空格进行拆分
            start = strarr[0];
            end = strarr[1];
            map.put("start", start);
            map.put("end", end);
        }

        //获取传过来的数据
        map.put("pName2", pName2);
        map.put("doctorName", doctorName);
        map.put("limit", limit);
        map.put("index", index);
        System.out.println("pName2:" + pName2 + "===start:" + start + "===end:" + end + "===doctorName:" + doctorName + "===limit:" + limit + "===index:" + index);
        try {
            //查询数据
            list = pr.selectAll_R(map);
            //获取数据总数
            int count = pr.dataTotal(map);
            if (list.size() > 0) {
                map.put("result", list);
                map.put("message", "挂号单信息查询成功");
                map.put("success", true);
                map.put("code", "0");
                map.put("count", count);        //查询到的数据的总数
                map.put("", "");
            } else {
                map.put("message", "挂号单信息查询失败");
                map.put("success", false);
                map.put("code", "0");
                map.put("count", 0);
                map.put("", "");
                map.put("result", null);
            }
        } catch (Exception e) {
            e.printStackTrace();
            map.put("message", "程序异常");
            map.put("success", false);
        }
        return map;
    }

    //根据id删除挂号单
    @RequestMapping("/delRegister")
    public Map delRegister(Integer id) {
        Map<String, Object> map = new HashMap<String, Object>();
        System.out.println("拿到的id是=========================" + id);
//       Integer i = Integer.parseInt(id);
        try {
            int count = pr.delRegister(id);
            if (count > 0) {
                map.put("message", "删除成功");
                map.put("success", true);
                map.put("result", count);
            } else {
                map.put("message", "删除失败");
                map.put("success", false);
            }
        } catch (Exception e) {
            e.printStackTrace();
            map.put("message", "程序异常");
            map.put("success", false);
        }
        return map;
    }

    //根据id批量删除挂号单
    @RequestMapping("/delRegisters")
    @Transactional
    public Map delRegisters(String id) {
        Map<String, Object> map = new HashMap<String, Object>();

        try {
            int count = pr.delRegisters(id);
            if (count > 0) {
                map.put("message", "批量删除成功");
                map.put("success", true);
                map.put("result", count);
            } else {
                map.put("message", "批量删除失败");
                map.put("success", false);
            }
        } catch (Exception e) {
            e.printStackTrace();
            //回滚
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            map.put("message", "程序异常");
            map.put("success", false);
        }
        return map;
    }


    /**
     * 查询用户中的医生，并且时间是在上下班时间内
     * 查询所有的诊室
     * @return
     */
    @RequestMapping("/selectDotor")
    public Map selectDotor() {
        Map<String, Object> map = new HashMap<String, Object>();
        //获取当前时间的时分秒
        Date date = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
        String date1 = dateFormat.format(date);
        //查询医生
        List<User1> list = pr.selectDotor(date1);
        System.out.println("controller=========================" + list.size());
        //查询诊室
        List<Division> list2 = pr.selectDivision();

        try {
            if (list.size() > 0 && list2.size() > 0) {
                map.put("message", "医生和诊室数据查询成功");
                map.put("success", true);
                map.put("result", list);
                map.put("result2", list2);
            } else {
                map.put("message", "当前没有在职医生");
                map.put("success", false);
            }
        } catch (Exception e) {
            e.printStackTrace();
            map.put("message", "查询医生和诊室数据程序异常");
            map.put("success", false);
        }
        return map;
    }

    //修改挂号的单和患者数据
    @RequestMapping("/UpdateR_P")
    public Map UpdateR_P(Register register) {
        Map<String, Object> map = new HashMap<String, Object>();
        int count = pr.UpdateP_R(register);
        try {
            if (count > 0) {
                map.put("message", "修改成功");
                map.put("success", true);
                map.put("result", count);
            } else {
                map.put("message", "修改失败");
                map.put("success", false);
            }
        } catch (Exception e) {
            e.printStackTrace();
            map.put("message", "修改程序出现异常");
            map.put("success", false);
        }
        return map;
    }

    /**
     * 判断当前时间属于哪个时间段,给对应时间段的就诊人数+1
     * 如果到达预定人数则给予提示
     * @return  当前时间的就诊人数和当前时间段
     * @throws ParseException
     */
    public Map judgeP_Namber() throws ParseException {
        Map<String,Object> map = new HashMap<>();
        boolean check = true;   //判断是否是次时间段
        int p_nomber = 0;       //当前时间的就诊人数
        Date now = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date start = sdf.parse(P_NamberUtil.am1);
        Date end = sdf.parse(P_NamberUtil.am2);
        check=P_NamberUtil.belongCalendar(now,start,end);
        int nom = 0;    //上午
        if (!check){
            Date start2 = sdf.parse(P_NamberUtil.pm1);
            Date end2 = sdf.parse(P_NamberUtil.pm2);
            check=P_NamberUtil.belongCalendar(now,start2,end2);
            nom = 1;    //下午
        }
        if (!check){
            Date start3 = sdf.parse(P_NamberUtil.night1);
            Date end3 = sdf.parse(P_NamberUtil.night2);
            check = P_NamberUtil.belongCalendar(now,start3,end3);
            nom = 2;    //晚上
        }
        if (!check){
            nom = 3;    //其余时间
        }
        map.put("data",p_nomber);   //当前就诊人数,未加上正在填写的患者
        switch (nom){
            case 1:
                if (P_NamberUtil.amPatientNambers==P_NamberUtil.amPatientNamber){
                    map.put("message","已经达到上午预定挂号人数");
                }
                p_nomber = ++P_NamberUtil.amPatientNambers;
                break;
            case 2:
                if (P_NamberUtil.pmPatientNambers==P_NamberUtil.pmPatientNamber){
                    map.put("message","已经达到下午预定挂号人数");
                }
                p_nomber = ++P_NamberUtil.pmPatientNambers;
                break;
            case 3:
                if (P_NamberUtil.nightPatientNambers==P_NamberUtil.nightPatientNamber){
                    map.put("message","已经达到晚上预定挂号人数");
                }
                p_nomber = ++P_NamberUtil.nightPatientNambers;
                break;
            default:
                p_nomber = ++P_NamberUtil.orderPatientNambers;
                break;
        }

        return map;
    }


    /**
     * 设置患者人数的全局静态变量
      * @param patientNamber
     * @return 操作的静态变量数
     */
    @RequestMapping("/patientNamber")
    public int setP_Namber( PatientNamber patientNamber){
        int count = 0;
        int am = patientNamber.getAmNamber();
        int pm = patientNamber.getPmNamber();
        int night = patientNamber.getNightNamber();
        if (am!=0){
            P_NamberUtil.amPatientNamber=am;
            count++;
        }
        if (pm!=0){
            P_NamberUtil.pmPatientNamber=pm;
            count++;
        }
        if (night!=0){
            P_NamberUtil.nightPatientNamber=night;
            count++;
        }
        System.out.println("程序走到这里："+count);

        return count;
    }


}
